package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyContent;
import cn.wolfcode.trip.base.domain.StrategyDetail;
import cn.wolfcode.trip.base.mapper.StrategyContentMapper;
import cn.wolfcode.trip.base.mapper.StrategyDetailMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IStrategyDetailService;
import cn.wolfcode.trip.base.util.UploadUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

@Service
public class StrategyDetailServiceImpl implements IStrategyDetailService {
    @Autowired
    private StrategyDetailMapper strategyDetailMapper;
    @Autowired
    private StrategyContentMapper contentMapper;

    /**
     * 查询所有攻略细节
     * @param qo 查询条件
     * @return
     */
    @Override
    public PageInfo<StrategyDetail> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List<StrategyDetail> detail = strategyDetailMapper.selectForList(qo);
        return new PageInfo<>(detail);
    }

    @Override
    public void saveOrUpdate(StrategyDetail detail, MultipartFile file) {
        if (detail.getState() == StrategyDetail.STATE_RELEASE) {
            detail.setReleaseTime(new Date());
        }
        //序号自增长
        if (detail.getSequence() == null) {
            Integer maxSequence = strategyDetailMapper.selectMaxSequence();
            detail.setSequence(maxSequence + 1);
        }
        if (file != null && file.getSize() > 0) {
            String fileName = UploadUtil.uploadQiniu(file);
            detail.setCoverUrl(fileName);
        }
        if (detail.getId() != null) {
            strategyDetailMapper.updateByPrimaryKey(detail);
            //更改文章内容
            StrategyContent content = detail.getContent();
            content.setId(detail.getId());
            contentMapper.updateByPrimaryKey(content);
        }else {
            strategyDetailMapper.insert(detail);
            //更改文章内容
            StrategyContent content = detail.getContent();
            content.setId(detail.getId());
            contentMapper.insert(content);
        }

    }

    @Override
    public StrategyDetail selectById(Long detailId) {
        return strategyDetailMapper.selectByPrimaryKey(detailId);
    }

    @Override
    public StrategyContent getContentById(Long id) {
        return contentMapper.selectByPrimaryKey(id);
    }
}
